package com.wu.project.admin.api;

import cn.hutool.crypto.SecureUtil;
import com.wu.project.admin.annotations.Authorization;
import com.wu.project.admin.component.JsonResult;
import com.wu.project.admin.entity.AddRoleMenuVO;
import com.wu.project.admin.entity.LoginVO;
import com.wu.project.admin.entity.UserEntity;
import com.wu.project.admin.service.ShiroUserService;
import com.wu.project.admin.util.JwtUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;

import javax.servlet.http.HttpServletRequest;


/**
 * @author xuan
 */
@Controller
@RequestMapping("/account")
public class AccountApi {

    Logger logger = LoggerFactory.getLogger(AccountApi.class);

    @Autowired
    ShiroUserService shiroUserService;

    @Value("${redirect.path}")
    String redirectVue;
    @Value("${redirect.login}")
    String redirectLogin;

    @GetMapping("/login")
    public ModelAndView adminLogin(LoginVO loginVO, Model model, HttpServletRequest request) {
        logger.error("重定向Vue:{},重定向登录:{}", redirectVue, redirectLogin);
        UserEntity userByName = shiroUserService.findUserByName(loginVO.getUsername());
        if (userByName == null) {
            model.addAttribute("error", "用户名不存在");
            return new ModelAndView(new RedirectView(redirectLogin + "/view/login.html?error=0"));
        }
        String salt = userByName.getSalt();
        String md5 = SecureUtil.md5(salt + loginVO.getPassword() + salt);
        if (md5.equals(userByName.getPwd())) {
            String roles = shiroUserService.getRolesByUid(userByName.getUid());
            String token = JwtUtil.Instance.createToken(String.valueOf(userByName.getUid()), roles, userByName.getUname());
            Long uid = userByName.getUid();
            return new ModelAndView(new RedirectView(redirectVue + "?token=" + token + "&userId=" + uid + "&role=" + roles));
        }
        model.addAttribute("error", "账号密码错误");
        return new ModelAndView(new RedirectView(redirectLogin + "/view/login.html?error=1"));
    }

    @GetMapping("/menu")
    @ResponseBody
    @Authorization
    public JsonResult userMenu(String uid) {
        return shiroUserService.getUserMenu(uid);
    }


    @Authorization
    @GetMapping("/allMenu")
    @ResponseBody
    public JsonResult allMenu() {
        return shiroUserService.getAllMenu();
    }

    @Authorization
    @PostMapping("/addRoleMenu")
    @ResponseBody
    public JsonResult addRoleMenu(@RequestBody AddRoleMenuVO addRoleMenuVO) {
        return shiroUserService.addRoleMenu(addRoleMenuVO);
    }
}
